package com.util;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by guanlei on 2018/1/22.
 * 版本号：4.5.3
 */
public class HttpClientUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static boolean httpPost(String url, Map<String,String> params){
        boolean result = false;
        if (StringUtils.isEmpty(url) || CollectionUtils.isEmpty(params)) return result;
        CloseableHttpClient httpClient = HttpClients.createDefault(); //创建请求对象
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> reqParams = new ArrayList<>();
        for (String key : params.keySet()) {
            reqParams.add(new BasicNameValuePair(key,params.get(key)));//构建请求入参
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(reqParams,"UTF-8")); //设置编码以防乱码
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            String responseEntity = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");//获取响应实体
            httpResponse.close();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = true;
                logger.debug("请求成功！接口返回结果为："+responseEntity);
                return result;
            }
            logger.debug("请求失败！接口返回结果为："+responseEntity);
        } catch (Exception e) {
            logger.error("请求出错！"+e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error("关闭请求出错！"+e);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "http://10.10.1.16:8080/cciaiweb/weblogin/signin";
        Map<String,String> params = new HashMap<>();
        params.put("userName","13816383527");
        params.put("password","123456");
        boolean result = HttpClientUtil.httpPost(url, params);
        System.out.println(result);
    }

}
